package com.writing.controller;

import com.writing.common.Result;
import com.writing.entity.Corpus;
import com.writing.entity.Novel;
import com.writing.service.CorpusService;
import com.writing.service.NovelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 语料库Controller
 */
@RestController
@RequestMapping("/novels/{novelId}/corpus")
public class CorpusController {

    @Autowired
    private CorpusService corpusService;

    @Autowired
    private NovelService novelService;

    /**
     * 验证小说访问权限
     */
    private boolean validateNovelAccess(Long novelId, Long userId) {
        Novel novel = novelService.getNovelDetail(userId, novelId);
        return novel != null;
    }

    /**
     * 获取小说的语料库列表
     */
    @GetMapping
    public Result<List<Corpus>> getCorpusList(@PathVariable Long novelId,
                                             HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            List<Corpus> corpusList = corpusService.getCorpusByNovelId(novelId);
            return Result.success(corpusList);
        } catch (Exception e) {
            return Result.error("获取语料库列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取语料库详情
     */
    @GetMapping("/{corpusId}")
    public Result<Corpus> getCorpus(@PathVariable Long novelId,
                                   @PathVariable Long corpusId,
                                   HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            Corpus corpus = corpusService.getCorpusById(corpusId, novelId);
            if (corpus == null) {
                return Result.error("语料库不存在");
            }
            return Result.success(corpus);
        } catch (Exception e) {
            return Result.error("获取语料库详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建语料库
     */
    @PostMapping
    public Result<Corpus> createCorpus(@PathVariable Long novelId,
                                      @RequestBody @Valid Corpus corpus,
                                      HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            corpus.setNovelId(novelId);
            Corpus createdCorpus = corpusService.createCorpus(corpus);
            return Result.success("创建成功", createdCorpus);
        } catch (Exception e) {
            return Result.error("创建语料库失败: " + e.getMessage());
        }
    }

    /**
     * 更新语料库
     */
    @PutMapping("/{corpusId}")
    public Result<Corpus> updateCorpus(@PathVariable Long novelId,
                                      @PathVariable Long corpusId,
                                      @RequestBody Corpus corpus,
                                      HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            corpus.setId(corpusId);
            corpus.setNovelId(novelId);
            Corpus updatedCorpus = corpusService.updateCorpus(corpus);
            if (updatedCorpus == null) {
                return Result.error("语料库不存在或无权限修改");
            }
            return Result.success(updatedCorpus);
        } catch (Exception e) {
            return Result.error("更新语料库失败: " + e.getMessage());
        }
    }

    /**
     * 删除语料库
     */
    @DeleteMapping("/{corpusId}")
    public Result<String> deleteCorpus(@PathVariable Long novelId,
                                      @PathVariable Long corpusId,
                                      HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            boolean deleted = corpusService.deleteCorpus(corpusId, novelId);
            if (!deleted) {
                return Result.error("语料库不存在或无权限删除");
            }
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除语料库失败: " + e.getMessage());
        }
    }
}
